package cc.rengu.igas.cops.core.service.trans.unionpay;

import cc.rengu.igas.cops.common.enums.RespCodeEnum;
import cc.rengu.igas.cops.facade.bean.BackC2bLimitInfo;
import cc.rengu.igas.cops.facade.request.BankC2bLimitQueryRequest;
import cc.rengu.igas.cops.facade.response.BankC2bLimitQueryResponse;
import cc.rengu.igas.share.core.model.UserInfo;
import cc.rengu.igas.share.core.realize.UserService;
import cc.rengu.igas.share.core.realize.impl.UserServiceImpl;
import cc.rengu.oltp.service.base.BizBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.TxnLimitStatisMapper;
import cc.rengu.oltp.service.common.dao.impl.TxnLimitStatisMapperImpl;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.TxnLimitStatis;
import cc.rengu.oltp.service.common.enums.CheckResultEnum;
import cc.rengu.oltp.service.common.enums.LimitTypeEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.*;
import cc.rengu.oltp.service.realize.TransCustomImpl;
import cc.rengu.oltp.service.realize.TransLimitService;
import cc.rengu.oltp.service.realize.impl.TransLimitServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 被扫---查询限额设置
 * 手机银行【ESB】—>支付系统
 * 返回限额设置，如果未设置，则将个人限额数据设为机构限额信息
 * 同时返回允许的最高限额
 * *
 * BizStatus：
 * 00-查询成功
 *
 * @author paykey
 * @version 1.0.0 创建时间：2020.07.08
 */
public class BankC2bLimitQueryService extends BizBaseService implements TransCustomImpl {


    @Override
    protected Object beforeBizProcess() throws Exception {
        BankC2bLimitQueryRequest bankC2bLimitQueryRequest = new BankC2bLimitQueryRequest();
        ConvertUtil.convertOutput(bankC2bLimitQueryRequest);
        return bankC2bLimitQueryRequest;
    }

    @Override
    protected BizResponse callBizService(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        // 录入参数
        BankC2bLimitQueryRequest bankC2bLimitQueryRequest = (BankC2bLimitQueryRequest) request;
        // 行号
        String instId = bankC2bLimitQueryRequest.getHeader().getInstId();

        // 此处客户号是核心客户号
        UserService userService = new UserServiceImpl();
        UserInfo userInfo = userService.getUserInfo(instId, bankC2bLimitQueryRequest.getAccNo(), bankC2bLimitQueryRequest.getHeader().getSession());
        if (userInfo == null || !userInfo.getUserStatus().equals("00")) {
            rglog.info("用户不存在,instId:<{}>, accoutNo:<{}>", instId, bankC2bLimitQueryRequest.getAccNo());
            throw new BizException(RespCodeEnum.USER_STATUS_ABNORMAL.getRespCode(), RespCodeEnum.USER_STATUS_ABNORMAL.getRespDesc());
        }
        // 核心客户号转换成用户编号
//        bankC2bLimitQueryRequest.setAccNo(userInfo.getUserId());

        String userId = userInfo.getUserId();

        String limitInst = instId + "|" + userInfo.getUserInst() + "|" + userId;

        /*  查询个人限额设置 */
        TransLimitInfo userLimit = userService.getUserLimitCfgInfo(instId, userId, userInfo.getUserInst(), bankC2bLimitQueryRequest.getBsnCode());

        //查询该机构限额
        TransLimitInfo orgLimit = userService.getUserLimitCfgInfo(instId, AppParamConstant.DEFAULT_INSTID, AppParamConstant.DEFAULT_INSTID, bankC2bLimitQueryRequest.getBsnCode());

        if (orgLimit == null) {
            rglog.error("行级<{}>限额<{}>设置不存在!", instId, bankC2bLimitQueryRequest.getBsnCode());
            throw new BizException(RespCodeEnum.ORG_LIMIT_CFG_NOT_FOUND.getRespCode(), RespCodeEnum.ORG_LIMIT_CFG_NOT_FOUND.getRespDesc());
        }

        //查询个人日支付金额
        String dayLimit = "0.00";

        TransLimitService transLimitService = new TransLimitServiceImpl(instId, txnInfo.getSrcTxnAuthCfg().getTxnNum(), null);
        TxnLimitStatisMapper txnLimitStatisMapper = new TxnLimitStatisMapperImpl();
        String statisDay = DateUtil.getCurrentDate();
        String staticPrimaryKey = LimitTypeEnum.C2B_QR.getLimitType() + limitInst + "*";
        TxnLimitStatis limitStatisList = txnLimitStatisMapper.selectTxnLimitStatisByPrimaryKey(instId, statisDay, "D", staticPrimaryKey);
        if (limitStatisList != null && !StringUtil.isEmptyOrNull(limitStatisList.getTotalTransAmt())) {
            dayLimit = limitStatisList.getTotalTransAmt();
        }

        //处理反馈信息
        BankC2bLimitQueryResponse bankC2bLimitQueryResponse = new BankC2bLimitQueryResponse();
        //日累计限额
        bankC2bLimitQueryResponse.setDatyLimit(dayLimit);

        if (userLimit != null) {
            //单笔限额
            bankC2bLimitQueryResponse.setSingleLimitMaxAmt(userLimit.getSingleLimitMaxAmt());
            //日累计限额
            bankC2bLimitQueryResponse.setDaylimitMaxAmt(userLimit.getDayLimitAmt());
        } else {
            //单笔限额
            bankC2bLimitQueryResponse.setSingleLimitMaxAmt(orgLimit.getSingleLimitMaxAmt());
            //日累计限额
            bankC2bLimitQueryResponse.setDaylimitMaxAmt(orgLimit.getDayLimitAmt());
        }

        //允许的单笔限额
        bankC2bLimitQueryResponse.setAllowSingleLimitMaxAmt(orgLimit.getSingleLimitMaxAmt());
        //允许的日累计限额
        bankC2bLimitQueryResponse.setAllowDaylimitMaxAmt(orgLimit.getDayLimitAmt());


        //解析验证方式参数
        List<BackC2bLimitInfo> authLimitList = new ArrayList<BackC2bLimitInfo>();
        Map<String, String> userAuthLimitMap = (userLimit == null || StringUtil.isEmptyOrNull(userLimit.getAuthLimitAmt())) ? null : JSON.parseObject(userLimit.getAuthLimitAmt(), Map.class);
        Map<String, String> orgAuthLimitMap = JSON.parseObject(orgLimit.getAuthLimitAmt(), Map.class);
        Set<String> orgKeys = orgAuthLimitMap.keySet();
        int i = 1;
        StringBuilder sb = new StringBuilder();
        sb.append("你当前支持的认证方式 ");
        for (String key : orgKeys) {

            String orgAmts = orgAuthLimitMap.get(key);

            if (!StringUtil.isEmptyOrNull(orgAmts)) {
                BackC2bLimitInfo info = new BackC2bLimitInfo();
                info.setAuthType(key);
                //设置允许设置的最高限额
                info.setAllowAuthDaylimitMaxAmt(orgAmts.split("\\|")[1]);
                info.setAllowAuthSingleLimitMaxAmt(orgAmts.split("\\|")[2]);

                //用户设置的限额信息，如果未设置则返回机构的限额信息
                String userAmts = userAuthLimitMap != null ? userAuthLimitMap.get(key) : null;
                if (!StringUtil.isEmptyOrNull(userAmts)) {
                    info.setStartAmt(userAmts.split("\\|")[0]);
                    info.setEndAmt(userAmts.split("\\|")[1]);
                    info.setAuthSingleLimitMaxAmt(userAmts.split("\\|")[2]);
                } else {
                    info.setStartAmt(orgAmts.split("\\|")[0]);
                    info.setEndAmt(orgAmts.split("\\|")[1]);
                    info.setAuthSingleLimitMaxAmt(orgAmts.split("\\|")[2]);
                }
                info.setId(String.valueOf(i));
                i++;
                //只给前端返回免密限额设置
                if (key.equals("00")) {
                    authLimitList.add(info);
                }
                // * 02 短信验证
                // * 03 软Ukey
                if ("02".equals(key)) {
                    sb.append("加密短信:单笔限额最大为:");
                    sb.append(info.getAuthSingleLimitMaxAmt());
                    sb.append("日累计限额最大为:");
                    sb.append(info.getEndAmt());
                }
            }
            bankC2bLimitQueryResponse.setLimitList(authLimitList);
        }
        sb.append("。");
        bankC2bLimitQueryResponse.setRemark(sb.toString());
        // 返回
        BizResponse bizResponse = new BizResponse();
        bizResponse.setResult(bankC2bLimitQueryResponse);// 返回结果
        bizResponse.setRspSysId(AppParamConstant.IGAS);

        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return bizResponse;
    }

    @Override
    protected void afterBizProcess(BizResponse response) throws Exception {
        BankC2bLimitQueryResponse retResponse = (BankC2bLimitQueryResponse) response.getResult();
        ConvertUtil.convertInput(retResponse);
    }

    @Override
    protected RiskMonitorInfo getRiskMonitorInfo() {
        return null;
    }

    @Override
    public ChannelCallCfg channelCallSceneDiscern(Object request, List<ChannelCallCfg> channelCallCfgList) throws Exception {
        return null;
    }

    @Override
    public CheckResultEnum channelCallPreCheck(Object request, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        return null;
    }

    @Override
    public TransStatusEnum channelCallResultProc(Object request, ChannelCallCfg channelCallCfg, TransStatusEnum transStatusEnum, Object channelResponse, OrderInfo needUpdateOrderInfo) throws Exception {
        return null;
    }
}
